export function base64ToFile(base64String, filename, mimeType = 'image/png') {
  // 去掉Base64字符串中的前缀（例如：data:image/png;base64,）
  const base64WithoutPrefix = base64String.replace(/^data:[a-z]+\/[a-z]+;base64,/, '');
  
  // 解码Base64字符串为原始二进制数据
  const binaryString = atob(base64WithoutPrefix);
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; ++i) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  
  // 创建Blob对象
  const blob = new Blob([bytes], { type: mimeType });
  
  // 创建File对象
  const file = new File([blob], filename, { type: mimeType });

  return file;
}

export function fileToBase64(file) {
  return new Promise((resolve, reject)=> {
    const reader = new FileReader();
  
    reader.onloadend = function () {
      // 读取完成后，reader.result 将包含转换后的Base64字符串
      resolve(reader.result);
    };
  
    reader.onerror = function() {
      reject();
    }

    reader.readAsDataURL(file);
  })
}

export async function imageUrlToBase64(url) {
  return fetch(url)
  .then(response => response.blob())
  .then(blob => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
  });
}